﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MyCommerce.ManagementBase.Common.Base.Common;
using MyCommerce.Presentation.Stores.Presenters;
using MyCommerce.Presentation.Stores.IViews;
using Innova.Microfinanzas.BusinessEntities;
using Innova.FoundationFramework.DataTypes;
using Innova.Microfinanzas.BusinessEntities.SystemEnums;

namespace MyCommerce.Windows.Stores.Views
{
    public partial class SalesChargeView : BaseForm, ISalesCharge
    {
        private SalesChargePresenter pPresenter;
        Nullable<long> idCustomer = null;
        MoneyEnum moneySelected = MoneyEnum.ExternalMoney;
        private decimal totalRealToPay = 0;

        #region CONSTRUCTOR

        public SalesChargeView()
        {
            InitializeComponent();
            pPresenter = new SalesChargePresenter(this);
        }

        #endregion

        #region ISalesCharge Members

        public decimal RateExchange
        {
            get
            {
                if (String.IsNullOrEmpty(fieldExchangeRate.Value.ToString()))
                    return 0;
                return Convert.ToDecimal(fieldExchangeRate.Value);
            }
            set
            {
                fieldExchangeRate.Value = value;
            }
        }

        public SalesOrder ObjSalesOrder
        {
            get
            {

                SalesOrder objSaleOrder = SalesOrder.CreateSalesOrder(0, DateTime.Now, string.Empty, Context.EmployeeId,
                    Context.DealerStoreId,RateExchange, totalInDollars, false, txtObservation.Text, (long)moneySelected,
                    totalRealToPay);
                objSaleOrder.IdCustomer = idCustomer;
                return objSaleOrder;
            }
        }

        private decimal totalInDollars = 0;
        List<SalesOrderDetail> pColSalesOrderDetail = new List<SalesOrderDetail>();
        public List<SalesOrderDetail> ColSalesOrderDetail
        {
            get
            {
                return pColSalesOrderDetail;
            }
            set
            {
                pColSalesOrderDetail = value;


                int count = 0;

                foreach (SalesOrderDetail item in value)
                {
                    totalInDollars += item.LineTotal;
                    count += item.OrderQuantity;
                }

                txtTotal.Text = totalInDollars.ToString("##,###0.00") + " $us";
                SetRealAmount(totalInDollars, MoneyEnum.ExternalMoney);
                lblTotalProducts.Text = count.ToString();
            }
        }

        public void SetRealAmount(decimal amount, MoneyEnum moneySelect)
        {
            string moneyPrefix = " $us";
            totalRealToPay = amount;
            if (moneySelect == MoneyEnum.LocalMoney)
                moneyPrefix = " Bs";
            txtTotalReal.Text = totalRealToPay.ToString("##,###0.00") + moneyPrefix;
            txtInCash.Focus();
        }

        public void CloseAndSetResult(bool result)
        {
            if (result)
                Context.ShowInformationMessageBox("La información se guardó correctamente.", "IMPORTANTE");
            Result = result;
            Close();
        }

        public event GenericEventHandler<string> OnLoadView;

        public event GenericEventHandler<decimal> OnChangeMoney;

        public event EventHandler OnSave;

        public event EventHandler OnCancel;

        #endregion

        #region EVENTS

        private void StoreView_Load(object sender, EventArgs e)
        {
            if (Parameter != null)
            {
                Dictionary<long, List<SalesOrderDetail>> paramDetail = new Dictionary<long, List<SalesOrderDetail>>();
                paramDetail = (Dictionary<long, List<SalesOrderDetail>>)Parameter;
                foreach (var item in paramDetail)
                {
                    if (item.Key == -1)
                        idCustomer = null;
                    else
                        idCustomer = item.Key;
                    ColSalesOrderDetail = item.Value;
                }                
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (Context.ShowQuestionMessageBox("¿Seguro que desea cancelar esta venta?", "Aviso") == System.Windows.Forms.DialogResult.Yes)
                if (OnCancel != null)
                    OnCancel(this, new EventArgs());
        }

        private void txtInCash_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter || e.KeyChar == (char)Keys.Tab)
            {
                SetAmountToReturn();
            }
        }

        private void btnChargeAndPrint_Click(object sender, EventArgs e)
        {

        }

        private void btnCharge_Click(object sender, EventArgs e)
        {
            if (OnSave != null)
                OnSave(this, new EventArgs());
        }

        /// <summary>
        /// DOLARES
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ultraButton2_Click(object sender, EventArgs e)
        {
            moneySelected = MoneyEnum.ExternalMoney;
            labelExchange.Visible = false;
            labelTotalToPay.CaptionText = "Total a Cobrar en $us :";
            ddlMoney.Appearance.BackColor = Color.SeaGreen;
            ddlMoney.Text = btnDollar.Text;
            ultraPopupControlContainer1.Close();
            txtTotal.Text = totalInDollars.ToString("##,###0.00") + " $us";
            SetRealAmount(totalInDollars, MoneyEnum.ExternalMoney);
            txtInCash.Value = 0;
            txtOutCash.Value = 0;            
        }

        /// <summary>
        /// BOLIVIANOS
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ultraButton1_Click(object sender, EventArgs e)
        {
            moneySelected = MoneyEnum.LocalMoney;
            labelExchange.Visible = true;
            labelTotalToPay.CaptionText = "Total a Cobrar en Bs :";
            ddlMoney.Appearance.BackColor = Color.Yellow;
            ddlMoney.Text = btnBolivian.Text;
            ultraPopupControlContainer1.Close();
            if (RateExchange > 0)
            {
                SetRealAmount(totalInDollars * RateExchange, MoneyEnum.LocalMoney);
            }
            else
            {
                if (OnChangeMoney != null)
                    OnChangeMoney(this, new GenericEventArgs<decimal>(totalInDollars));
            }
            txtInCash.Value = 0;
            txtOutCash.Value = 0;            
        }
        
        private void fieldExchangeRate_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter || e.KeyChar == (char)Keys.Tab)
            {
                SetRealAmount(totalInDollars * RateExchange, MoneyEnum.LocalMoney);
                SetAmountToReturn();
            }
        }

        private void SetAmountToReturn()
        {
            if (!string.IsNullOrEmpty(txtInCash.Value.ToString()))
            {
                decimal cambio = Convert.ToDecimal(txtInCash.Value) - totalRealToPay;
                if (cambio < 0)
                    cambio = 0;
                txtOutCash.Text = cambio.ToString("##,###0.00");
            }
        }

        #endregion
    }
}
